<?php
use Base\AdminController;
use Illuminate\Support\Str;
use JetBrains\PhpStorm\NoReturn;

class ExamtopicController extends AdminController
{
    protected string $table = 'exam_topics';

    protected string $model = "examTopic";

    /**
     * 初始化
     */
    #[NoReturn] public function init(): void
    {
        if (Request::input("title")) {
            $this->where[] = ['title','like', '%'.Request::input("title").'%'];
        }
        $this->routeWhiteLst = ['examtopic@getoptions'];
        parent::init();
    }

    /**
     * 获取列表页数据
     * @return void
     */
    #[NoReturn] public function indexAction(): void
    {
        try {
            $sort = Request::input("sort");
            $orderBy = match ($sort)
            {
                "-id"=>'asc',
                default => 'desc',
            };
            if (Request::input("is_hid") !== null) {
                $this->where[] = ['is_hid','=',Request::input("is_hid")];
            }
            if (isset($this->where['sorts'])) {
                $sorts = $this->where['sorts'];
                unset($this->where['sorts']);
            }else{
                $sorts = NULL;
            }
            $sql = App::make($this->getModelMame())
                ->with(['subject'])
                ->when($this->includes,function ($query,$value) {
                    $query->with($value);
                })->where($this->where)
                ->when($this->whereIn,function ($query,$value){
                    foreach ($value as $item) {
                        $query->whereIn($item[0], $item[1]);
                    }
                });
            $sql->when($sorts,function ($query,$value){
                $query->orderBy("sort",$value);
            });
            unset($this->where['sorts']);
            $data = $sql->orderBy("id",$orderBy)->paginate(Request::input("limit",10),['*'],NULL,Request::input("p",1));
            $_data = collect($data->items())->toArray();
            foreach ($_data as $key=>$vo) {
                $_data[$key]['type_d'] = dictByName('topic_type')[$vo['type']];
                $_data[$key]['subject_title'] = $vo['subject']['title'];
            }
            $result = [
                'items' => $_data,
                'total'=>$data->total(),
                'per_page' => $data->perPage(),
                'page' => $data->currentPage()
            ];
            $this->apiSuccess($result,"获取成功",20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    #[NoReturn] public function getOptionsAction(): void
    {
        $data = dict('topic_type');
        $result = [];
        foreach ($data as $key=>$vo) {
            $result[] = [
                'value'=>(int)$vo,
                'label'=>$key
            ];
        }
        $this->apiSuccess($result,"获取成功",20000);
    }

    /**
     * 显示
     * @return void
     */
    #[NoReturn] protected function operate(): void
    {
        try {
            $info = ExamTopicModel::query()->with(["options"])->where('id', Request::input("ids"))->first();
            if (!$info) $this->apiError("数据不存在");
            $this->apiSuccess($info->toArray(),"获取成功",20000);
        }catch (Exception $e) {
            $this->apiError($e->getMessage());
        }
    }

    /**
     * 修改
     * @return void
     */
    protected function update(): void
    {
        try {
            $params  = Request::all();
            $this->cleanCache();
            if (Request::input("id") !== null) {
                ExamTopicOptionModel::where("topic_id",Request::input("id"))->delete();
                $insert = [];
                foreach ($params['options'] as $vo) {
                    $insert[] = [
                        'uuid'=>(string)Str::uuid(),
                        'topic_id'=>Request::input("id"),
                        'title'=>$vo['title'],
                        'is_right'=>$vo['is_right'],
                        'created_at'=>date("Y-m-d H:i:s")
                    ];
                }
                ExamTopicOptionModel::insert($insert);
                unset($params['options']);
                ExamTopicModel::query()->where("id",Request::input("id"))->update($params);
                $this->apiSuccess([],"更新成功",20000);
            }else {
                $params['uuid'] = (string)Str::uuid();
                $params['created_at'] = date("Y-m-d H:i:s");
                if (DB::schema()->hasColumn($this->table, "org_id")) {
                    $params['org_id'] = $this->org['id'];
                }
                if (DB::schema()->hasColumn($this->table, "user_id")) {
                    $params['user_id'] = $this->member_id;
                }
                $options = $params['options'];
                unset($params['options']);
                $res =  ExamTopicModel::query()->insertGetId($params);
                $insert = [];
                foreach ($options as $vo) {
                    $insert[] = [
                        'uuid'=>(string)Str::uuid(),
                        'topic_id'=>$res,
                        'title'=>$vo['title'],
                        'is_right'=>$vo['is_right'],
                        'created_at'=>date("Y-m-d H:i:s")
                    ];
                }
                ExamTopicOptionModel::insert($insert);
                $info =  ExamTopicModel::query()->with(["options"])->where('id',$res)->first();
                $this->apiSuccess( $info->toArray(),"新增成功",20000);
            }
        } catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }
}
